# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :jwt_tool.py
# @Time      :2022/7/22 14:10
# @Author    :吕华龙


# 生成token
import time

import jwt
from flask import current_app


class JWT_tool:
    # 创建token
    def create_token(self, payload, exp, secret=None):
        if not secret:
            secret = current_app.config['SECRET_KEY']
        print("payload:", payload)
        payload['ex'] = int(time.time()) + exp

        token = jwt.encode(payload, key=secret, algorithm="HS256")

        print("生成token成功")

        return token

    # 校验token
    def ver_token(self, token, secret=None):
        if not secret:
            secret = current_app.config['SECRET_KEY']

        if not token:
            return None

        payload = jwt.decode(token, key=secret, algorithms="HS256")

        if not payload:
            payload = None

        print("解析token成功", payload)

        return payload


if __name__ == '__main__':
    from app import app

    with app.app_context():
        j = JWT_tool()
        # token = j.create_token({
        #     "id": 1,
        #     "name": "小小"
        # }, exp=3600)
        # print("token-----------", token)
        payload = j.ver_token(
            "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwibmFtZSI6Ilx1NWMwZlx1NWMwZiIsImV4IjoxNjU4ODkyNzExfQ.anpoGA4lyUiSAEoNTPrUjS4Jq7gfQC6hvkZFcmiApfg")
        print("payload", payload)
